package com.suoluo.zenadmin.service.country;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.dao.country.CountryDAO;
import com.suoluo.zenadmin.oss.OSSService;
import com.suoluo.zenadmin.oss.OSSService.OSSImageException;
import com.suoluo.zenadmin.service.ServiceException;
import com.suoluo.zenadmin.vo.country.ContinentVO;
import com.suoluo.zenadmin.vo.country.CountryVO;

public class CountryServiceImpl implements CountryService {
	@Autowired
	private CountryDAO countryDAO;

	@Resource(name = "ossService")
	private OSSService ossService;

	@SuppressWarnings("rawtypes")
	@Override
	public List<Map> findListCountry(int startPage, int rows) {

		return countryDAO.findListCountry(startPage, rows);
	}

	@Override
	public int findCountryCount() {
		return countryDAO.findCountryCount();
	}

	@Override
	public void saveCountry(CountryVO countryVO) {
		// FileEntry file = null;
		String imageName = null;
		try {
			imageName = ossService.putImage(countryVO.getFlagFile());
			countryVO.setCountryOrigFlag(imageName);

			countryVO.setCountrySort(new Date());
			countryDAO.insert(countryVO);
		} catch (OSSImageException e) {
			throw new ServiceException(CommonResp.FAIL_CODE, "保存国旗失败", e);
		} catch (Exception e) {
			ossService.deleteImage(imageName);
			throw new ServiceException(CommonResp.FAIL_CODE, "保存国家失败", e);
		}

	}

	@Override
	public List<ContinentVO> findListContinent() {
		return countryDAO.findListContinent();
	}

	@Override
	public CountryVO findCountryById(int countryId) {
		return countryDAO.findCountryById(countryId);
	}

	@Override
	public void update(CountryVO countryVO) {
		String imgName = null;
		try {
			String imgurl = countryVO.getCountryOrigFlag();
			MultipartFile mfile = countryVO.getFlagFile();
			if (mfile != null && !mfile.isEmpty()) {
				imgName = ossService.updateImage(mfile, imgurl);
				countryVO.setCountryOrigFlag(imgName);
			}
			countryVO.setCountrySort(new Date());
			countryDAO.update(countryVO);
		} catch (OSSImageException e) {
			throw new ServiceException(CommonResp.FAIL_CODE, "图片更新失败!", e);
		} catch (Exception e) {
			ossService.deleteImage(imgName);
			throw new ServiceException(CommonResp.FAIL_CODE, "国家修改失败", e);
		}
	}

	@Override
	public void delete(CountryVO country) {

		// 判断该国家是否被目的地和新闻引用，如果被引用不可以删除
		int res = countryDAO.findCountryForeignDestAndNews(country
				.getCountryId());
		if (res > 0) {
			throw new ServiceException(CommonResp.FAIL_CODE,
					"该国家已被目的地或新闻引用，不可以删除！");
		}
		//没有被引用删除图片
		ossService.deleteImage(country.getCountryOrigFlag());
		//删除数据
		countryDAO.delete(country.getCountryId());
	}

}
